package jdk7;

import java.awt.print.Book;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class JDBC4_1 {
	public void abortConnection() throws SQLException {
		Connection connection = DriverManager.getConnection("jdbc:derby://localhost/java7book");
		ThreadPoolExecutor executor = new DebugExecutorService(2, 10, 60, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>());
		connection.abort(executor);
		executor.shutdown();
		try {
			executor.awaitTermination(5, TimeUnit.MINUTES);
			System.out.println(executor.getCompletedTaskCount());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static class DebugExecutorService extends ThreadPoolExecutor {
		public DebugExecutorService(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
				BlockingQueue<Runnable> workQueue) {
			super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		}

		@Override
		public void beforeExecute(Thread t, Runnable r) {
			System.out.println("清理任务：" + r.getClass());
			super.beforeExecute(t, r);
		}
	}

	public static void main(String[] args) {
		JDBC4_1 ca = new JDBC4_1();
		try {
			ca.abortConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

//自动关闭

class SetSchema {
	public void setSchema() throws SQLException {

		try (Connection connection = DriverManager.getConnection("jdbc:derby://localhost/java7book")) {
			connection.setSchema("DEMO_SCHEMA");
			try (Statement stmt = connection.createStatement();
					ResultSet rs = stmt.executeQuery("SELECT * FROM author")) {

				while (rs.next()) {
					System.out.println(rs.getString("name"));
				}
			}
		}
	}

	public static void main(String[] args) {
		SetSchema ss = new SetSchema();
		try {
			ss.setSchema();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

//自动映射

class UseSQLData {

	public void useSQLData() throws SQLException {
		try (Connection connection = DriverManager.getConnection("jdbc:derby://localhost/java7book")) {
			Map<String, Class<?>> typeMap = new HashMap<String, Class<?>>();
			typeMap.put("java7book.Book", Book.class);
			try (Statement stmt = connection.createStatement();
					ResultSet rs = stmt.executeQuery("SELECT * FROM book")) {
				while (rs.next()) {
					System.out.println(rs.getObject(1, Book.class));
				}
			}
		}
	}

	public static void main(String[] args) {
		UseSQLData usd = new UseSQLData();
		try {
			usd.useSQLData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
